package com.example.music.fragment;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaMetadataRetriever;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SearchView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.music.R;
import com.example.music.activity.MusicActivity;
import com.example.music.activity.MusicDemoActivity;
import com.example.music.adapter.IndexAdapter;
import com.example.music.adapter.SongAdapter;
import com.example.music.model.AppConstants;
import com.example.music.model.Song;
import com.example.music.utils.PinyinUtil;
import com.example.music.utils.SectionItemDecoration;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SongsFragment extends Fragment {
    private static final String TAG = "SongsFragment";
    private RecyclerView recyclerView;
    private RecyclerView indexRecyclerView;
    private SongAdapter songAdapter;
    private IndexAdapter indexAdapter;
    private List<Song> songList = new ArrayList<>();
    private Map<Integer, String> sectionMap = new HashMap<>();

    public enum SortType { BY_SONG }

    public static SongsFragment newInstance(SortType sortType) {
        SongsFragment songsFragment = new SongsFragment();
        Bundle args = new Bundle();
        args.putSerializable("sort_type", sortType);
        songsFragment.setArguments(args);
        return songsFragment;
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        AppConstants.num=2;
        View view = inflater.inflate(R.layout.fragment_songs, container, false);
        recyclerView = view.findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        indexRecyclerView = view.findViewById(R.id.index_recycler_view);
        indexRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        // 加载本地歌曲并按规则排序
        loadSongs();

        // 搜索功能
        SearchView searchView = view.findViewById(R.id.search_view);
        if (searchView != null) {
            searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                @Override
                public boolean onQueryTextSubmit(String query) {
                    return false;
                }

                @Override
                public boolean onQueryTextChange(String newText) {
                    songAdapter.getFilter().filter(newText);

                    // 添加延迟确保过滤完成
                    new Handler(Looper.getMainLooper()).postDelayed(() -> {
                        updateSectionMap();
                        recyclerView.invalidateItemDecorations(); // 关键：强制重绘
                        indexAdapter.notifyDataSetChanged();
                    }, 100);
                    return true;
                }
            });
        } else {
            Log.e(TAG, "SearchView not found in the layout");
        }

        return view;
    }

    private void loadSongs() {
        try (Cursor cursor = requireContext().getContentResolver().query(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                new String[]{
                        MediaStore.Audio.Media.TITLE,
                        MediaStore.Audio.Media.ARTIST,
                        MediaStore.Audio.Media.ALBUM,
                        MediaStore.Audio.Media.DATA,
                        MediaStore.Audio.Media.DURATION
                },
                MediaStore.Audio.Media.IS_MUSIC + " != 0",
                null,
                null
        )) {
            if (cursor == null) {
                Log.e(TAG, "Failed to get cursor");
                return;
            }

            while (cursor.moveToNext()) {
                String title = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
                String artist = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
                String album = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));
                String filePath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
                long duration = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION));

                Song song = new Song(title, artist, album, filePath);
                song.setDuration(duration);

                // 获取专辑封面
                Bitmap albumCover = getAlbumArt(filePath);
                song.setAlbumCover(albumCover);
                // 获取歌词文件
                String lyricsPath = findLyricsFile(filePath);
                song.setLyricsPath(lyricsPath);

                songList.add(song);
            }
        } catch (Exception e) {
            Log.e(TAG, "Error loading songs", e);
        }

        // 中文拼音排序
        Collections.sort(songList, Comparator.comparing(song -> PinyinUtil.toPinyin(song.getTitle())));

        // 更新节索引映射
        updateSectionMap();

        // 设置Adapter
        songAdapter = new SongAdapter(songList);
        songAdapter.setOnItemClickListener(new SongAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(Song song) {
                Intent intent = new Intent(requireContext(), MusicActivity.class);
                intent.putExtra("position", String.valueOf(songList.indexOf(song)));
                intent.putExtra("songList", new ArrayList<>(songList)); // Pass a copy of the list
                startActivity(intent);
            }
        });
        recyclerView.setAdapter(songAdapter);

        // 添加节索引装饰
        SectionItemDecoration decoration = new SectionItemDecoration(50, 30, new SectionItemDecoration.SectionCallback() {
            @Override
            public String getSectionHeader(int position) {
                String header = sectionMap.getOrDefault(position, "");
                Log.d(TAG, "getSectionHeader position: " + position + ", header: " + header);
                return header;
            }
        });
        recyclerView.addItemDecoration(decoration);

        // 初始化字母索引适配器
        String[] alphabet = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
        indexAdapter = new IndexAdapter(alphabet);
        indexAdapter.setOnItemClickListener(letter -> {
            for (int i = 0; i < songList.size(); i++) {
                if (sectionMap.containsKey(i) && sectionMap.get(i).equals(letter)) {
                    recyclerView.smoothScrollToPosition(i);
                    break;
                }
            }
        });
        indexRecyclerView.setAdapter(indexAdapter);
    }

    private void updateSectionMap() {
        sectionMap.clear();
        char lastChar = '\0';

        for (int i = 0; i < songList.size(); i++) {
            String title = songList.get(i).getTitle();
            String pinyinTitle = PinyinUtil.toPinyin(title);

            // 处理空拼音情况
            if (pinyinTitle == null || pinyinTitle.isEmpty()) {
                pinyinTitle = "#"; // 使用特殊字符标记
            }

            char firstChar = Character.toUpperCase(pinyinTitle.charAt(0));

            // 处理非字母字符
            if (!Character.isLetter(firstChar)) {
                firstChar = '#';
            }

            if (firstChar != lastChar) {
                sectionMap.put(i, String.valueOf(firstChar));
                lastChar = firstChar;
            }
        }
    }

    private Bitmap getAlbumArt(String filePath) throws IOException {
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            retriever.setDataSource(filePath);
            byte[] artBytes = retriever.getEmbeddedPicture();
            if (artBytes != null) {
                return BitmapFactory.decodeByteArray(artBytes, 0, artBytes.length);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            retriever.release();
        }
        return null;
    }

    private String findLyricsFile(String songFilePath) {
        File songFile = new File(songFilePath);
        File directory = songFile.getParentFile();
        if (directory == null || !directory.exists() || !directory.isDirectory()) {
            return null;
        }

        FilenameFilter lrcFilter = (dir, name) -> name.equalsIgnoreCase(songFile.getName().replace(".mp3", ".lrc"));
        File[] lrcFiles = directory.listFiles(lrcFilter);

        if (lrcFiles != null && lrcFiles.length > 0) {
            return lrcFiles[0].getAbsolutePath();
        }

        return null;
    }
}